package com.hos.db.manager;

import com.gexin.rp.sdk.base.uitls.MD5Util;
import com.hos.db.create.art.ArticleContentEntity;
import com.hos.db.create.art.ArticleTable;
import com.hos.db.entity.ArtEntity;
import com.hos.db.entity.UserSysEntity;
import com.hos.net.req.art.ArtCreateReq;
import com.hos.net.req.art.ArtDeleteReq;
import com.hos.net.req.art.ArtUpdateReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.JsonUtile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//文章管理
public class ArtManager {

    private static ArtManager userPatsManager;

    public static ArtManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new ArtManager();
        }
        return userPatsManager;
    }

    /**
     * 添加文章
     *
     * @param jdbcTemplate
     * @param req
     * @return
     */
    public String artAddReq(JdbcTemplate jdbcTemplate, UserSysEntity sys, ArtCreateReq req) {

        String response = new MsgHint("添加失败").toJson();

        String sql = "INSERT INTO " + ArticleTable.tableName
                + "("
                + ArticleTable.tableArtId + ","
                + ArticleTable.tableArtTitle + ","
                + ArticleTable.tableArtImgCover + ","
                + ArticleTable.tableArtContent + ","
                + ArticleTable.tableArtOwner + ","
                + ArticleTable.tableArtOwnerId + ","
                + ArticleTable.tableArtAuthor + ","
                + ArticleTable.tableArtCreateTime + ","
                + ArticleTable.tableArtUpdateTime
                + ")"
                + " VALUES (?,?,?,?, ?, ?,?, ?,?)";
        List<ArticleContentEntity> artContents = req.artContents;
        String json = "";
        if (artContents != null && artContents.size() > 0) {
            for (int i = 0; i < artContents.size(); i++) {
                ArticleContentEntity art = artContents.get(i);
                String artMsg = art.artMsg;
                artMsg = artMsg.replaceAll("\"", "&quot;");
                art.artMsg = artMsg;
            }
            json = JsonUtile.obj2Json(artContents);
        }
        try {
            Date time = new Date();
            String t1 = DateUtile.getDateFormat(time, DateUtile.DATA_FORMAT_YMD_HMS);
            String artId = MD5Util.getMD5Format(sys.getSysId() + t1);
            int status = jdbcTemplate.update(sql,
                    new Object[]{artId, req.artTitle, req.artImgCover, json,
                            sys.getSysName(), sys.getSysId(),
                            sys.getSysName(), time, time});
            if (status > 0) {
                ArtEntity art = new ArtEntity();
                art.artAuthor = sys.getSysName();
                art.artTitle = req.artTitle;
                art.artId = artId;
                art.artContents = req.artContents;
                BaseResponse res = new BaseResponse<ArtEntity>();
                res.obj = art;
                response = res.toJson("0", "添加成功");
            }
        } catch (Exception e) {
            DLog.e("添加失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 所有者获取文章
     *
     * @param jdbcTemplate
     * @param artOwnerId   所有者id
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     * @param hasNextPage  判断是否有下一页
     */
    public List<ArtEntity> getArts(JdbcTemplate jdbcTemplate, String artOwnerId, int pageNo, int pageSize,
                                   boolean hasNextPage) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        //SELECT * FROM user ORDER BY create_time,id LIMIT 6,2;
        //SELECT * FROM articles WHERE art_owner_id =  18868714258  ORDER BY art_update_time limit 0 , 3
        String sql = "SELECT * FROM " + ArticleTable.tableName
                + " WHERE "
                + ArticleTable.tableArtOwnerId + " = " + artOwnerId
                + " ORDER BY " + ArticleTable.tableArtUpdateTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);

        List<ArtEntity> user = artQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    public int getArts(JdbcTemplate jdbcTemplate, String artOwnerId) {
        //select count(*) from user_docs
        String sql = "SELECT count(*) FROM " + ArticleTable.tableName
                + " WHERE "
                + ArticleTable.tableArtOwnerId + " = " + artOwnerId;
        int count = jdbcTemplate.queryForInt(sql);
        return count;
    }

    /**
     * 获取文章
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<ArtEntity> getArtsr(JdbcTemplate jdbcTemplate, int pageNo, int pageSize
            , boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String sql = "SELECT * FROM " + ArticleTable.tableName
                + " ORDER BY " + ArticleTable.tableArtUpdateTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<ArtEntity> user = artQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    /**
     * 获取发布的文章
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<ArtEntity> getIssueArts(JdbcTemplate jdbcTemplate, int pageNo, int pageSize
            , boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String sql = "SELECT * FROM " + ArticleTable.tableName
                + " WHERE "
                + ArticleTable.tableArtIssue + " = " + "1"
                + " ORDER BY " + ArticleTable.tableArtUpdateTime
                + " DESC "
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<ArtEntity> user = artQuery(jdbcTemplate, sql);
        if (user == null) {
            user = new ArrayList();
        }
        return user;
    }

    //删除文章
    public String deleteArtReq(JdbcTemplate jdbcTemplate, String ownerId, ArtDeleteReq art) {
       /* String sql = "SELECT * FROM " + ArticleTable.tableName
                + " WHERE "
                + ArticleTable.tableArtId + " = " + art.artId;
        List<ArtEntity> arts = artQuery(jdbcTemplate, sql);
        if (arts == null || arts.size() == 0) {
            return new MsgHint("文章不存在").toJson();
        }*/
        String sql = "DELETE  FROM " + ArticleTable.tableName
                + " WHERE "
                + ArticleTable.tableArtId + " = '" + art.artId + "'"
                + " AND "
                + ArticleTable.tableArtOwnerId + " = '" + ownerId + "'";
        int state = jdbcTemplate.update(sql);
        if (state == 0) {
            return new MsgHint("文章不存在").toJson();
        }
        return new MsgHint("0", "删除成功").toJson();
    }

    //修改文章状态
    public String updateArtReq(JdbcTemplate jdbcTemplate, String ownerId, String artId, String state,
                               String issue) {
        String update = "";
        if (state != null) {
            update += " , " + ArticleTable.tableArtState + " = '" + state + "'";
        }
        if (issue != null) {
            update += " , " + ArticleTable.tableArtIssue + " = '" + issue + "'";
        }
        update = update.replaceFirst(" , ", "");
        String sql = "UPDATE " + ArticleTable.tableName
                + " SET "
                + update
                + " WHERE "
                + ArticleTable.tableArtId + " = '" + artId + "'"
                + " AND "
                + ArticleTable.tableArtOwnerId + " = '" + ownerId + "'";

        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //修改文章
    public String updateArtReq(JdbcTemplate jdbcTemplate, String ownerId, ArtUpdateReq art) {
        String update = "";
        String artTitle = art.artTitle;
        if (artTitle != null && artTitle != "") {
            update += " , " + ArticleTable.tableArtTitle + " = '" + artTitle + "'";
        }
        String artImgCover = art.artImgCover;
        if (artTitle != null && artTitle != "") {
            update += " , " + ArticleTable.tableArtImgCover + " = '" + artImgCover + "'";
        }
        List<ArticleContentEntity> artContents = art.artContents;
        if (artContents != null) {
            String json = "";
            if (artContents.size() > 0) {
                for (int i = 0; i < artContents.size(); i++) {
                    ArticleContentEntity artEntity = artContents.get(i);
                    String artMsg = artEntity.artMsg;
                    artMsg = artMsg.replaceAll("\"", "&quot;");
                    artEntity.artMsg = artMsg;
                }
                json = JsonUtile.obj2Json(artContents);
            }
            DLog.e("修改之后的json："+json);
            update += " , " + ArticleTable.tableArtContent + " = '" + json + "'";
        }
        if (update.equals("")) {
            return new MsgHint("请设置要修改的参数").toJson();
        }
        update = update.replaceFirst(" , ", "");
        update += " , " + ArticleTable.tableArtUpdateTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'";
        //
        String sql = "UPDATE " + ArticleTable.tableName
                + " SET "
                + update
                + " WHERE "
                + ArticleTable.tableArtId + " = '" + art.artId + "'"
                + " AND "
                + ArticleTable.tableArtOwnerId + " = '" + ownerId + "'";

        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "修改成功").toJson();
        }
        return new MsgHint("修改失败").toJson();
    }

    //查询文章
    private List<ArtEntity> artQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<ArtEntity> arts = null;
        try {
            arts = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(ArtEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return arts;
    }
}
